<?php
/*
 * SME.Model.Behaviors.Clickable, Part of BIT.SMEJOB CMS
 *
 * update the click count of a certain data entity, such as articles,
 * easy to install and configure, the first cake Behavior of myself
*/

class ClickableBehavior extends ModelBehavior{
    var $name = 'Clickable';
    var $__defaultOptions = array(
        'key' => 'id',
        'clickable' => 'clicks'
    );
    var $mapMethods = array('/click/' => 'click');

    /**
     * Setup behaviour.
     *
     * @param Model $Model
     * @param array $settings
     */
    public function setup(&$Model, $settings = array()){
        if(!isset($this->settings[$Model->alias])){
            if(empty($settings)){
                $this->settings[$Model->alias] = $this->__defaultOptions;
            }elseif(is_array($settings)){
                $this->settings[$Model->alias] = array_merge($this->__defaultOptions, $settings);
            }
        }
    }

    /**
     * Register a click in the database.
     *
     * @param Model $Model
     * @param mixed $key
     */
    public function click(&$Model, $key = null, $settings = null){
        $_settings = array();

        if(isset($this->settings[$Model->alias]))
            $_settings = $this->settings[$Model->alias];

        if(is_array($settings))
            $_settings = array_merge($_settings, $settings);

        if(!isset($_settings['clickable']) || !isset($_settings['key'])){
            $this->log('Miscofigured clickcount behavior!', LOG_WARNING);
            return;
        }

        if(!$Model->hasField($_settings['key']))
            return;

        if(!$Model->hasField($_settings['clickable']))
            return;

        if(empty($key))
            $key = $Model->id;

        if(empty($key)){
            $this->log('Invalid call to clickcount behavior!', LOG_WARNING);
            return;
        }

        $Model->updateAll(
            array ($_settings['clickable'] => $Model->alias.'.'.$_settings['clickable'].' + 1'),
            array ($Model->alias.'.'.$_settings['key'] => $key)
        );
    }
}

?>